package it.getta.vicinometro.utils;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageButton;

public class BlinkImageButton extends ImageButton {
	
	public static final int DEFAULT_BLINKING_INTERVAL = 1000;
	
	private Handler mHandler;
	
	private int mOnImageResId;
	private int mOffImageResId;
	private boolean mStopBlinking = false;
	private int mBlinkingInterval = DEFAULT_BLINKING_INTERVAL;

	public BlinkImageButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public BlinkImageButton(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public BlinkImageButton(Context context) {
		super(context);
	}
	
	public void setImages(int onImageResId, int offImageResId) {
		mOnImageResId = onImageResId;
		mOffImageResId = offImageResId;
	}
	
	public void startBlinking() {
		mStopBlinking = false;
		Thread blinkThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(!mStopBlinking) {
					setImageResourceAsync(mOnImageResId);
					invalidateAsync();
					try {
						Thread.sleep(mBlinkingInterval);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					setImageResourceAsync(mOffImageResId);
					invalidateAsync();
					try {
						Thread.sleep(mBlinkingInterval);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		blinkThread.start();
	}
	
	public void setImageResourceAsync(final int resId) {
		mHandler.post(new Runnable() {
			
			@Override
			public void run() {
				BlinkImageButton.super.setImageResource(resId);
				
			}
		});
		
	}
	
	public void setHandler(Handler handler) {
		mHandler = handler;
	}
	
	public void invalidateAsync() {
		mHandler.post(new Runnable() {
			
			@Override
			public void run() {
				BlinkImageButton.super.invalidate();
			}
		});
	}
	
	public void stopBlinking() {
		mStopBlinking = true;
	}

	public int getBlinkingInterval() {
		return mBlinkingInterval;
	}

	public void setBlinkingInterval(int mBlinkingInterval) {
		this.mBlinkingInterval = mBlinkingInterval;
	}

}
